package com.xxxx.seckill.rabbitmq;

import com.xxxx.seckill.pojo.SeckillMessage;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IGoodsService;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.utils.JsonUtil;
import com.xxxx.seckill.vo.GoodsVo;
import com.xxxx.seckill.vo.RespBean;
import com.xxxx.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {
    @Autowired
    IGoodsService iGoodsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    IOrderService iOrderService;

@RabbitListener(queues = "seckillQueue")
public void receive(String message){
    log.info ("接收到的消息："+message);
    SeckillMessage seckillMessage = JsonUtil.jsonStr2Object (message, SeckillMessage.class);
    Long goodId = seckillMessage.getGoodId ( );
    User user = seckillMessage.getUser ( );
//   判断库存
    GoodsVo goodsVoByGoodsId = iGoodsService.findGoodsVoByGoodsId (goodId);
//    if (goodsVoByGoodsId.getStockCount ()<1){
//        return;
//    }

//        判断是否重复抢购
    SeckillOrder seckillOrder = (SeckillOrder)redisTemplate.opsForValue ( ).get ("order:" + user.getId ( ) + ":" + goodId);
    if (seckillOrder!=null){
        return;
    }
//    下单
    iOrderService.seckill (user,goodsVoByGoodsId);
}
}
